package com.sg.file.transform.provider.center;

import com.sg.file.common.conf.VisibleFileSizeConf;
import com.sg.file.transform.api.dto.TransformReqeust;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;

import java.io.IOException;

/**
 * Created by asus on 2018/6/28.
 */
@Slf4j
public class ImageTranscode implements TransformCode {

    @Override
    public void doTransform(TransformReqeust transformReqeust) throws IOException {
        VisibleFileSizeConf.Size size = VisibleFileSizeConf
                .getImageSize(transformReqeust.getTransformToFileSizeType());

        if(size == null){
            //为null表示原图转化
            transcoding(transformReqeust.getOriginFilePath()
                    ,transformReqeust.getTransformToFileSuffixType()
                    ,transformReqeust.getTransformFilePath());

        }else{
            transcoding(transformReqeust.getOriginFilePath()
                    ,transformReqeust.getTransformToFileSuffixType()
                    ,size.getWidth().intValue()
                    ,size.getHeight().intValue()
                    ,transformReqeust.getTransformFilePath());
        }
    }

    /**
     * 转码并输出
     *
     * @param source
     *            源文件路径
     * @param suffix
     *            后缀
     * @param transFilePath
     *            转换文件路径
     * @throws IOException
     */
    public static void transcoding(String source, String suffix, String transFilePath) throws IOException {
        Thumbnails.of(source).scale(1f).outputFormat(suffix).toFile(transFilePath);
    }

    /**
     * 转码缩放并输出
     *
     * @param source
     *            源文件路径
     * @param suffix
     *            后缀
     * @param width
     *            文件宽
     * @param height
     *            文件高
     * @param transFilePath
     *            转换文件路径
     * @throws IOException
     */
    public static void transcoding(String source, String suffix
            , int width, int height
            , String transFilePath) throws IOException {
        Thumbnails.of(source).forceSize(width, height).outputFormat(suffix).toFile(transFilePath);
    }
}
